from django.shortcuts import render
from django.views import View
from apps.verifications.libs.captcha.captcha import captcha
from django_redis import get_redis_connection
from django import http
import logging, random
from celery_tasks.sms.tasks import ccp_send_sms_code

from apps.verifications.libs.yuntongxun.ccp_sms import CCP

# Create your views here.

logger = logging.getLogger('django')


class ImageCodeView(View):
    def get(self, request, uuid):
        text, image = captcha.generate_captcha()
        redis_conn = get_redis_connection('verify_code')
        redis_conn.setex('img_%s' % uuid, 300, text)
        return http.HttpResponse(image, content_type='image/jpg')


class SMSCodeView(View):
    def get(self, request, mobile):
        # 判断手机号是否频繁发送短信
        redis_conn = get_redis_connection('verify_code')
        send_flag = redis_conn.get('send_flag_%s' % mobile)
        if send_flag:
            return http.JsonResponse({'code': 400, 'errmsg': '频繁发送短信验证码'})

        # 接收参数
        image_code_client = request.GET.get('image_code')
        uuid = request.GET.get('image_code_id')

        # 校验参数
        if not all([image_code_client, uuid]):
            return http.JsonResponse({'code': 400, 'errmsg': '缺少必穿参数'})

        # 处理图形验证码
        image_code_server = redis_conn.get('img_%s' % uuid)
        if not image_code_server:
            return http.JsonResponse({'code': 400, 'errmsg': '图形验证码失效'})
        redis_conn.delete('img_%s' % uuid)
        image_code_server = image_code_server.decode()
        if image_code_client.lower() != image_code_server.lower():
            return http.JsonResponse({'code': 400, 'errmsg': '图形验证码错误'})

        # 短信验证码相关处理
        random_num = random.randint(0, 999999)
        sms_code = '%06d' % random_num
        logger.info(sms_code)
        redis_conn = get_redis_connection('verify_code')
        # redis_conn.setex('sms_%s' % mobile, 300, sms_code)
        # redis_conn.setex('send_flag_%s' % mobile, 60, 1)
        # CCP().send_template_sms(mobile, [sms_code, 4], 1)

        # 使用pipeline管道来操作redis数据库的数据写入
        pl = redis_conn.pipeline()
        pl.setex('sms_%s' % mobile, 300, sms_code)
        pl.setex('send_flag_%s' % mobile, 60, 1)
        pl.execute()

        # 使用异步任务发送短信验证码
        ccp_send_sms_code.delay(mobile, sms_code)

        # 响应结果
        return http.JsonResponse({'code': 0, 'errmsg': '发送短信验证码'})



